package org.jeecg.modules.demo.hd.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.zhyd.oauth.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.hd.entity.AppConfig;
import org.jeecg.modules.demo.hd.entity.AppUserShareDetail;
import org.jeecg.modules.demo.hd.service.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.hd.vo.ShareExchangeVo;
import org.jeecg.modules.demo.hd.vo.UserShareDetailViewVo;
import org.jeecg.modules.demo.hd.vo.total.ChildUserGoldInputVo;
import org.jeecg.modules.demo.hd.vo.total.UserGoldDetailViewVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 工币明细
 * @Author: jeecg-boot
 * @Date: 2025-04-30
 * @Version: V1.0
 */
@Api(tags = "app_user_share_detail")
@RestController
@RequestMapping("/hd/appUserShareDetail")
@Slf4j
public class AppUserShareDetailController extends JeecgController<AppUserShareDetail, IAppUserShareDetailService> {
    @Autowired
    private IAppUserShareDetailService appUserShareDetailService;
    @Autowired
    private IAppUserShareMainService shareMainService;

    @Autowired
    private IAppUserGoldMainService goldMainService;

    @Autowired
    private IAppUserGoldDetailService goldDetailService;
    @Autowired
    private IAppConfigService appConfigService;

    /**
     * 分页列表查询
     *
     * @param appUserShareDetail
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "app_user_share_detail-分页列表查询", notes = "app_user_share_detail-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<AppUserShareDetail>> queryPageList(AppUserShareDetail appUserShareDetail,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
//        QueryWrapper<AppUserShareDetail> queryWrapper = QueryGenerator.initQueryWrapper(appUserShareDetail, req.getParameterMap());
        LambdaQueryWrapper<AppUserShareDetail> queryWrapper = Wrappers.lambdaQuery();

        Page<AppUserShareDetail> page = new Page<AppUserShareDetail>(pageNo, pageSize);
        IPage<AppUserShareDetail> pageList = appUserShareDetailService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param appUserShareDetail
     * @return
     */
    @AutoLog(value = "app_user_share_detail-添加")
    @ApiOperation(value = "app_user_share_detail-添加", notes = "app_user_share_detail-添加")
    @RequiresPermissions("hd:app_user_share_detail:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody AppUserShareDetail appUserShareDetail) {
        appUserShareDetailService.save(appUserShareDetail);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param appUserShareDetail
     * @return
     */
    @AutoLog(value = "app_user_share_detail-编辑")
    @ApiOperation(value = "app_user_share_detail-编辑", notes = "app_user_share_detail-编辑")
    @RequiresPermissions("hd:app_user_share_detail:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody AppUserShareDetail appUserShareDetail) {
        appUserShareDetailService.updateById(appUserShareDetail);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "app_user_share_detail-通过id删除")
    @ApiOperation(value = "app_user_share_detail-通过id删除", notes = "app_user_share_detail-通过id删除")
    @RequiresPermissions("hd:app_user_share_detail:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        appUserShareDetailService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "app_user_share_detail-批量删除")
    @ApiOperation(value = "app_user_share_detail-批量删除", notes = "app_user_share_detail-批量删除")
    @RequiresPermissions("hd:app_user_share_detail:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.appUserShareDetailService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "app_user_share_detail-通过id查询")
    @ApiOperation(value = "app_user_share_detail-通过id查询", notes = "app_user_share_detail-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<AppUserShareDetail> queryById(@RequestParam(name = "id", required = true) String id) {
        AppUserShareDetail appUserShareDetail = appUserShareDetailService.getById(id);
        if (appUserShareDetail == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(appUserShareDetail);
    }

    @ApiOperation(value = "兑换", notes = "兑换")
    @PostMapping(value = "/exchange")
    public Result<String> exchange(@RequestBody ShareExchangeVo vo) {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 查看当天是否已经兑换过，每个用户每天只允许兑换一次。
        if (this.appUserShareDetailService.exitCurrentDayUserDuiHuan(currentUser.getId())) {
            return Result.error("每用户每日仅限兑换一次！");
        }
        if (vo.getShareNum() < 1) {
            return Result.error("兑换工币数量必须大于1！");
        }
        AppConfig config = this.appConfigService.getConfig();
        Double gbRate = config.getGbRate();
        Double kouGoldNum = vo.getShareNum() * gbRate;                          // 扣除用户金币
        double userGold = goldMainService.queryUserGold(currentUser.getId());   //获取用户金币数量
        if (kouGoldNum > userGold) {
            return Result.error("金币数量不足，请联系客服！");
        }
        // 添加兑换记录
        updateDetail(currentUser.getId(), vo.getShareNum(), "", "1", "金币兑换");
        // 扣除用户金币
        goldDetailService.exchangeShare(currentUser.getId(), -kouGoldNum);
        return Result.OK("兑换成功！");
    }

    @ApiOperation(value = "邀请奖励", notes = "邀请奖励")
    @GetMapping(value = "/InvitationRewards")
    public Result<String> InvitationRewards() {
        // 获取当前用户的邀请人信息
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String parentUser = this.appUserShareDetailService.findParentUser(currentUser.getId());
        if (StringUtils.isEmpty(parentUser)) {
            return Result.OK("未找到邀请人信息！！");
        }
        // 判断当前邀请人是否已经发放过该笔记录
        if (!appUserShareDetailService.exitParentUserInvitationRewards(parentUser, currentUser.getId())) {
            updateDetail(parentUser, 5, currentUser.getId(), "2", "邀请人实名认证获得");
        } else {
            return Result.OK("邀请奖励已发放！！");
        }
        return Result.OK("成功！！");
    }

    private boolean updateDetail(String userId, Integer num, String data, String shareType, String name) {
        // 发放工币
        AppUserShareDetail shareDetail = new AppUserShareDetail();
        shareDetail.setUserId(userId);
        shareDetail.setShareNum(num);
        shareDetail.setShareType(shareType);
        shareDetail.setName(name);
        shareDetail.setStatus("1");
        shareDetail.setData(data);
        this.appUserShareDetailService.save(shareDetail);
        // 更新用户主表信息
        shareMainService.updateShareMain(userId, num);
        return true;
    }


    @ApiOperation(value = "获取用户金币获得明细", notes = "获取用户金币获得明细")
    @GetMapping(value = "/queryChildUserGoldByUserId")
    public Result<IPage<UserShareDetailViewVo>> queryChildUserGoldByUserId(ChildUserGoldInputVo vo,
                                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest req) {
//        IPage<UserGoldDetailViewVo> data = appUserShareDetailService.getUserGoldDetailList(vo, new Page(pageNo, pageSize));

        return Result.OK(null);
    }
}
